<script setup>
import { onMounted, ref } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import { ElMessage, ElMessageBox } from 'element-plus'
import { Command } from '@tauri-apps/api/shell';
import { open as openDialog } from '@tauri-apps/api/dialog';
import { appDataDir } from '@tauri-apps/api/path';
import { type } from '@tauri-apps/api/os';
import { getTemplates } from '../request'

const greetMsg = ref("");
const dir = ref("");
const projectName = ref("");
const cloneLoading = ref(false);
const curRepoIndex = ref(0);
const dialogVisible = ref(false)
const projects = ref([]);
const curThumbs = ref([]);

async function greet() {
  // Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
  greetMsg.value = await invoke("greet", { name: name.value });
}

async function open_clone_repo(doc, repoIndex) {
  if (isCloned(doc)) {
    openCloned(doc)
    return
  }
  if (dir.value == '') {
    ElMessage({
      message: '请选择工作目录',
      type: 'error',
    })
    return
  }
  let repo_name = ''
  if (projectName.value == '') {
    repo_name = doc.substring(doc.lastIndexOf('/') + 1).split('.')[0];
  }
  curRepoIndex.value = repoIndex;
  let spliter = '\\'
  // mac系统
  const osType = await type();
  if (osType.indexOf('Darwin') != -1) {
    spliter = '/'
  }
  const clone_dir = projectName.value == '' ? dir.value + spliter + repo_name : dir.value + spliter + projectName.value;
  console.log('local_dir:', clone_dir)
  const exists = await invoke("check_folder_exists", { folder: clone_dir });
  if (+exists) {
    ElMessage({
      message: '本地已存在该目录，请重新输入',
      type: 'error',
    })
    return
  }
  do_clone(['clone', doc, clone_dir])
}

async function do_clone(params) {
  console.log(params)
  const command = new Command('run-git', params);
  command.on('close', data => {
    console.log(`command finished with code ${data.code} and signal ${data.signal}`)
    cloneLoading.value = false;
    ElMessage({
      message: '仓库克隆成功',
      type: 'success',
    })
    let clonedProjects = JSON.parse(localStorage.getItem('clonedProjects') || '{}');
    clonedProjects[params[1]] = params[2];
    localStorage.setItem('clonedProjects', JSON.stringify(clonedProjects));
  });
  command.on('error', error => {
    console.error(`command error: "${error}"`)
    cloneLoading.value = false;
  });
  command.stdout.on('data', line => console.log(`command stdout: "${line}"`));
  command.stderr.on('data', line => console.log(`command stderr: "${line}"`));
  cloneLoading.value = true;
  const child = await command.spawn();
  console.log('pid:', child.pid);
}

function isCloned(url) {
  let clonedProjects = JSON.parse(localStorage.getItem('clonedProjects') || '{}');
  if (clonedProjects[url]) {
    return true
  }
  return false
}

async function openCloned(url) {
  let clonedProjects = JSON.parse(localStorage.getItem('clonedProjects') || '{}');
  if (clonedProjects[url]) {
    console.log('open dir:', clonedProjects[url])
    await invoke("open_directory", { path: clonedProjects[url] })
  }
}

async function del_local(url) {
  let clonedProjects = JSON.parse(localStorage.getItem('clonedProjects') || '{}');
  if (clonedProjects[url]) {
    console.log('del dir:', clonedProjects[url])
    ElMessageBox.alert('确定删除吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: true,
      showCancelButton: true,
      showClose: false,
      callback: async (action) => {
        if (action === 'confirm') {
          const status = await invoke("del_directory", { path: clonedProjects[url] })
          if (+status) {
            ElMessage({
              type: 'success',
              message: `操作成功`,
            })
            delete clonedProjects[url];
            localStorage.setItem('clonedProjects', JSON.stringify(clonedProjects));
            const projectsTemp = projects.value
            projects.value = []
            projects.value = projectsTemp
          } else {
            ElMessage({
              type: 'error',
              message: `操作失败`,
            })
          }
        }
      },
    })

  }
}

async function chooseDir() {
  const dir_path = await openDialog({
    directory: true,
    multiple: false,
    defaultPath: await appDataDir(),
  });
  dir.value = dir_path;
  localStorage.setItem('local_dir', dir_path);
}

async function reset_path() {
  dir.value = '';
  localStorage.removeItem('local_dir');
}

async function showPics(pics) {
  curThumbs.value = pics;
  dialogVisible.value = true;
}

const handleCommand = async (command, url) => {
  if (command == 'clear_git') {
    let clonedProjects = JSON.parse(localStorage.getItem('clonedProjects') || '{}');
    if (clonedProjects[url]) {
      let spliter = '\\'
      // mac系统
      const osType = await type();
      if (osType.indexOf('Darwin') != -1) {
        spliter = '/'
      }
      const gitDir = clonedProjects[url] + `${spliter}.git`
      console.log('clear git:', gitDir)
      const status = await invoke("del_directory", { path: gitDir })
      if (+status) {
        ElMessage({
          type: 'success',
          message: `操作成功`,
        })
      } else {
        ElMessage({
          type: 'error',
          message: `操作失败`,
        })
      }
    }
  }
}

onMounted(async () => {
  if (localStorage.getItem('local_dir')) {
    dir.value = localStorage.getItem('local_dir');
  }
  const results = await getTemplates();
  projects.value = JSON.parse(results.data || [])
})
</script>

<template>
  <div class="content">
    <div class="local-setting">
      <div class="result">
        <div class="label">工作目录</div>
        <el-input v-model="dir" placeholder="请选择本地工作目录或手动输入" />
        <el-button type="primary" class="choose-dir" @click="chooseDir">选择</el-button>
        <el-button @click="reset_path" plain>重置</el-button>
      </div>
      <div class="result">
        <div class="label">项目名</div>
        <el-input v-model="projectName" placeholder="请输入项目名，可不填(默认使用仓库名)" />
      </div>
    </div>
    <div class="cards-box">
      <el-card class="pro-card" v-for="(project, proIndex) in projects" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>{{ project.name }}</span>
            <el-link :href="project.git" type="info" target="_blank">查看仓库</el-link>
            <div class="status-tag" v-if="isCloned(project.git)">已下载</div>
          </div>
        </template>
        <div class="cover" @click="showPics(project.thumbs)">
          <el-carousel :interval="4000" type="card" indicator-position="none" height="200px">
            <el-carousel-item class="page-item" v-for="(pic, index) in project.thumbs" :key="index">
              <img class="cover-img" :src="pic.picUrl" />
              <div class="page-name" justify="center">{{ pic.pageName }}</div>
            </el-carousel-item>
          </el-carousel>
        </div>
        <template #footer>
          <div class="op-btn">
            <div>
              <el-button :loading="cloneLoading && proIndex == curRepoIndex" type="primary"
                @click="open_clone_repo(project.git, proIndex)">{{ isCloned(project.git) ? '打开目录' : '克隆仓库' }}</el-button>
            </div>
            <el-dropdown class="del-dir" v-if="isCloned(project.git)" split-button type="primary"
              @click="del_local(project.git)" @command="handleCommand($event, project.git)">
              删除目录
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="clear_git">清除.git文件夹</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-card>
    </div>


    <el-dialog v-model="dialogVisible" title="预览" width="90%">
      <el-carousel className="preview-box" :interval="4000">
        <el-carousel-item class="page-item" v-for="(pic, index) in curThumbs" :key="index">
          <img class="cover-img" :src="pic.picUrl" />
          <div class="page-name" justify="center">{{ pic.pageName }}</div>
        </el-carousel-item>
      </el-carousel>
    </el-dialog>

  </div>
</template>

<style lang="less" scoped>
.el-tabs--border-card>.el-tabs__content {
  height: 100%;
}

:deep(.el-dialog__headerbtn) {
  box-shadow: none !important;
}

.preview-box {
  overflow: hidden;
  min-height: 50vh;

  .page-item {
    text-align: center;

    .cover-img {
      object-fit: contain;
      height: 100%;
    }
  }
}

.content {
  padding: 15px;

  .cards-box {
    display: flex;
    align-content: flex-start;
    flex-wrap: wrap;
  }

  .pro-card {
    // width: 400px;
    margin: 0 20px 15px 0;
    flex-basis: 31%;
    position: relative;

    .card-header {
      padding-top: 3px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .status-tag {
        position: absolute;
        right: 0;
        top: 0;
        font-size: 10px;
        padding: 3px 5px 3px;
        line-height: 12px;
        background: #95d475;
        color: #fff;
        border-radius: 0 4px 0 4px;
      }
    }
  }

  .cover {
    max-width: 100%;

    .page-item {

      .cover-img {
        object-fit: cover;
        width: 100%;
      }

      .page-name {
        color: #4a4a4a;
        position: absolute;
        bottom: 0;
        height: 20px;
        font-size: 12px;
        line-height: 20px;
        z-index: 10;
        width: 100%;
        text-align: center;
      }
    }


  }

  .local-setting {
    margin-bottom: 15px;

    .result {
      display: flex;
      align-content: flex-start;
      align-items: center;
      margin-bottom: 10px;

      .label {
        min-width: 75px;
        margin-right: 10px;
        color: #606266;
      }

      .choose-dir {
        margin-left: 10px;
      }
    }
  }


  .data-box {
    overflow-y: auto;
    background: #fff;
    max-height: 800px;
  }

  .btns {
    margin-top: 20px;
  }

  .op-btn {
    display: flex;
    align-content: flex-start;
    justify-content: space-between;

    .del-dir {
      margin-left: 10px;
    }
  }
}
</style>
